using System;
using System.Windows.Forms;

namespace needle.UI.Controls.Flat.Windows.Forms.Helpers
{
    internal class ControlUtilities
	{
		private ControlUtilities()
		{
		}

		public static void RemoveAll(Control control)
		{
			if ((control != null) && (control.Controls.Count > 0))
			{
                Button tempButton = null;
                Form parentForm = control.FindForm();
                
				if (parentForm != null)
				{
					tempButton = new Button();
					tempButton.Visible = false;

					parentForm.Controls.Add(tempButton);

					parentForm.ActiveControl = tempButton;
                }

				control.Controls.Clear();

                if (parentForm != null)
                {
					tempButton.Dispose();
					parentForm.Controls.Remove(tempButton);
				}
			}
		}

		public static void Remove(Control.ControlCollection coll, Control item)
		{
			if ((coll != null) && (item != null))
			{
                Button tempButton = null;
                Form parentForm = item.FindForm();

				if (parentForm != null)
				{
					tempButton = new Button();
					tempButton.Visible = false;

					parentForm.Controls.Add(tempButton);

					parentForm.ActiveControl = tempButton;
                }
                
				coll.Remove(item);

                if (parentForm != null)
                {
					tempButton.Dispose();
					parentForm.Controls.Remove(tempButton);
				}
			}
		}

		public static void RemoveAt(Control.ControlCollection coll, int index)
		{
			if (coll != null)
			{
				if ((index >= 0) && (index < coll.Count))
				{
					Remove(coll, coll[index]);
				}
			}
		}
    
        public static void RemoveForm(Control source, Form form)
        {
            ContainerControl container = source.FindForm() as ContainerControl;
            
            if (container == null)
                container = source as ContainerControl;

            Button tempButton = new Button();

            if (container != null)
            {            
                tempButton.Visible = false;

                container.Controls.Add(tempButton);

                container.ActiveControl = tempButton;
            }
            
            form.Parent = null;
 
            if (container != null)
            {
                tempButton.Dispose();
                container.Controls.Remove(tempButton);
            }
        }
    }
}